import {Inject, Injectable} from '@angular/core';

import {nullCheck} from '../helpers/validate';

export enum LOADING_STATE {
  'NON',
  'LOADED',
  'LOADING'
}

export class ScriptLoaderConfig {
  public ak = '';
}

window._scriptLoadState = LOADING_STATE.NON;
window._loadingCallbacks = [];

@Injectable()
export class ScriptLoader {
  private _config: ScriptLoaderConfig;
  constructor(@Inject(ScriptLoaderConfig)config: ScriptLoaderConfig) {

    nullCheck(config.ak, 'ak must be provided');
    this._config = config;
  }

  public load(cb: () => void): void {
    console.log('load script');
    if (window._scriptLoadState === LOADING_STATE.LOADED) {
      switchDisplay('baidu-map .baidu-map-instance', 'block');
      switchDisplay('baidu-map .baidu-map-offline', 'none');
      return cb();
    }

    if (window._scriptLoadState === LOADING_STATE.LOADING) {
      window
        ._loadingCallbacks
        .push(cb);
      return;
    }

    window._scriptLoadState = LOADING_STATE.LOADING ;
    window._loadingCallbacks.push(cb);

    // &callback=baidumapinit

    const MAP_URL = `http://api.tianditu.com/api?v=4.0`;
    window.mapinit = () => {
      console.log('window.mapinit');
      console.log(window.T);
      window._scriptLoadState = LOADING_STATE.LOADED;
      switchDisplay('baidu-map .baidu-map-instance', 'block');
      switchDisplay('baidu-map .baidu-map-offline', 'none');
      window._loadingCallbacks
        .forEach((c: () => void) => {
          console.log('_loadingCallbacks');
          c();
        });


    };
    appendScriptTag(MAP_URL);

    // window.mapinit();
    /*
    setTimeout(() => {
      window.mapinit();
    }, 2000);
    */
  }
}

function appendScriptTag(url: string) {
  const script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = url;
 // script.async = false;
  script.onerror = () => {
    switchDisplay('baidu-map .baidu-map-offline', 'block');
    switchDisplay('baidu-map .baidu-map-instance', 'none');
    document
      .body
      .removeChild(script);

    setTimeout(() => {
      console.log('添加url');
      appendScriptTag(url);
    }, 30000);
  };
  document
    .body
    .appendChild(script);

    script.onload = () => {
        console.log('地图js加载完毕');
        window.mapinit();
      };
/*
    setTimeout(() => {
        window.mapinit();
      }, 2000);
      */
}

function switchDisplay(selector: string, state: string) {
  Array
    .prototype
    .slice
    .call(document.querySelectorAll(selector))
    .forEach((node: HTMLElement) => {
      node.style.display = state;
    });
}
